package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonTool {
	private static GsonBuilder builder = new GsonBuilder();
	private static Gson gson = builder.create();
	
	/**
	 * 对象转json字符串
	 * @param obj
	 * @return
	 */
	public static String objectToJson(Object obj) {
		return gson.toJson(obj);
	}
	
	/**
	 * json文件转对象
	 * @param filename 文件名
	 * @param type 对象类型
	 * @return
	 */
	public static <T> T fileToObject(String filename, Class<T> type) {
		File file = new File(filename);
		Reader reader;
		try {
			reader = new FileReader(file);
			return gson.fromJson(reader, type);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
